package com.apigen.platform.controller;

import com.apigen.platform.common.Result;
import com.apigen.platform.dto.LoginResponse;
import com.apigen.platform.security.UserPrincipal;
import com.apigen.platform.service.IAuthService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户控制器
 *
 * @author API Generator Platform
 * @since 2025-09-26
 */
@Slf4j
@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
@Tag(name = "用户管理", description = "用户信息相关接口")
public class UserController {

    private final IAuthService authService;

    @GetMapping("/me")
    @Operation(summary = "获取当前用户信息", description = "获取当前登录用户的详细信息")
    public Result<Map<String, Object>> getCurrentUser() {
        try {
            UserPrincipal currentUser = getCurrentUserPrincipal();
            if (currentUser == null) {
                return Result.error("用户未登录");
            }
            
            // 获取完整的用户信息
            LoginResponse.UserInfo userInfo = authService.getCurrentUserInfo(currentUser.getUserId());
            
            // 转换为前端期望的格式
            Map<String, Object> result = new HashMap<>();
            result.put("username", userInfo.getAccountName()); // 前端期望的是username字段
            result.put("roles", userInfo.getRoles() != null ? userInfo.getRoles() : new String[]{"user"}); // 确保roles不为null
            result.put("userId", userInfo.getUserId());
            result.put("nickName", userInfo.getNickName());
            result.put("email", userInfo.getEmail());
            result.put("phone", userInfo.getPhone());
            result.put("isAdmin", userInfo.getIsAdmin());
            result.put("lastLoginTime", userInfo.getLastLoginTime());
            result.put("permissions", userInfo.getPermissions());
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取用户信息失败: {}", e.getMessage(), e);
            return Result.error("获取用户信息失败: " + e.getMessage());
        }
    }

    /**
     * 获取当前登录用户
     */
    private UserPrincipal getCurrentUserPrincipal() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof UserPrincipal) {
            return (UserPrincipal) authentication.getPrincipal();
        }
        return null;
    }
}
